package com.guide.hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class HelloServer {

    private static final Logger logger = LoggerFactory.getLogger(HelloServer.class);

    public void handle(Socket socket) {
        logger.info("A client is connected.");
        try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
            Message message = (Message) objectInputStream.readObject();
            logger.info("Service has received message: " + message.getContent());
            message.setContent("This is a message from server.");
            objectOutputStream.writeObject(message);
            objectOutputStream.flush();
        } catch (IOException e) {
            logger.info("An error has occurred when reading or writing an object.");
        } catch (ClassNotFoundException e) {
            logger.info("The class called Message has not been found!");
        }
    }

    public static void main(String[] args) {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        int port = 6666;
        try (ExecutorService threadPool = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100), threadFactory);
             ServerSocket serverSocket = new ServerSocket(port)) {
            logger.info("Service is ready.");
            while (true) {
                Socket socket = serverSocket.accept();
                threadPool.execute(() -> {
                    HelloServer helloServer = new HelloServer();
                    helloServer.handle(socket);
                });
            }
        } catch (IOException e) {
            logger.info("An error has occurred when creating the ServerSocket or connecting a client.");
        }
    }
}
